package com.lennon.spring.cloud.ms.user;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.persistence.*;


@SpringBootApplication
@EnableEurekaClient
public class UserApp {

    public static void main(String[] args) {
        SpringApplication.run(UserApp.class, args);
    }
}

interface UserRepository extends JpaRepository<User, Long> {
}

@Component
class DataInit implements ApplicationRunner {

    @Autowired
    UserRepository userRepository;


    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        userRepository.save(new User(null, 22, "lennon1", "lennon fan1", 220));
        userRepository.save(new User(null, 21, "lennon2", "lennon fan2", 220));
        userRepository.save(new User(null, 20, "lennon3", "lennon fan3", 220));
        userRepository.save(new User(null, 29, "lennon4", "lennon fan4", 220));
    }
}


@RestController
class UserController {

    @Autowired
    UserRepository userRepository;

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable Long id) {
        User user = userRepository.findOne(id);
        return user;
    }

    @GetMapping(value = "/hello")
    public String getUser() {
        return "hello";
    }

    @PostMapping("/user")
    public User postUser(@RequestBody User user)
    {
        return user;
    }

    @GetMapping("/user-get")
    public User postUserGet(User user)
    {
        return user;
    }
}

@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "tbl_user")
class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private int age;

    private String username;

    private String name;

    private double balance;
}